<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <ToHeader :list="list" @importation="importation"></ToHeader>
    <!-- 主体部分 -->
    <ToMain
      :list="rendering"
      @deleteItem="deleteItem"
      @choose="choose"
    ></ToMain>
    <!-- 底部部分 -->
    <ToFooter
      :list="list"
      @purge="purge"
      @switchover="switchover"
    ></ToFooter>
  </section>
</template>

<script>
import ToHeader from '@/components/ToHeader.vue'
import ToMain from '@/components/ToMain.vue'
import ToFooter from '@/components/ToFooter.vue'

export default {
  components: {
    ToHeader,
    ToMain,
    ToFooter
  },
  data () {
    return {
      char: '',
      list: JSON.parse(localStorage.getItem('information')) || [
        { id: 1, checked: false, task: '读万卷书' },
        { id: 2, checked: true, task: '行万里路' }
      ]
    }
  },
  methods: {
    importation (literals) {
      const newObj = {
        id: +new Date(),
        checked: false,
        task: literals
      }
      this.list = [newObj, ...this.list]
    },
    deleteItem (id) {
      this.list = this.list.filter(item => item.id !== id)
    },
    choose (id) {
      this.list.forEach(item => {
        if (item.id === id) {
          item.checked = !item.checked
        }
      })
    },
    purge () {
      this.list = this.list.filter(item => !item.checked)
    },
    switchover (data) {
      this.char = data
    }
  },
  computed: {
    rendering () {
      switch (this.char) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter(item => !item.checked)
        case 'completed':
          return this.list.filter(item => item.checked)
        default:
          return this.list
      }
    }
  },
  watch: {
    list: {
      deep: true,
      handler (newValue) {
        localStorage.setItem('information', JSON.stringify(newValue))
      }
    }
  }
}
</script>

<style></style>
